<template>
    <div class="file-list-container">
        <el-card class="unified-card" shadow="hover">
            <div class="card-header">
                <div class="header-row first-row">
                    <el-button type="primary" icon="Back" @click="goBack" class="back-btn">返回知识库</el-button>
                </div>
                <div class="header-row second-row">
                    <h2 class="knowbase-title">知识库：{{ knowbaseName }}</h2>
                </div>
                <div class="header-row third-row">
                    <div class="search-section">
                        <el-input v-model="searchForm.keyword" placeholder="请输入文档名称" clearable suffix-icon="Search"
                            class="search-input" />
                    </div>

                    <div class="action-buttons">
                        <el-button type="primary" @click="handleSearch" icon="Search">查询</el-button>
                        <el-button @click="resetSearch" icon="Refresh">重置</el-button>

                        <el-upload action="#" :show-file-list="false" :before-upload="beforeUpload"
                            :http-request="handleUpload" :on-progress="handleUploadProgress">
                            <el-button type="primary" icon="Upload" class="upload-btn">上传文档</el-button>
                        </el-upload>
                    </div>

                    
                </div>

                 <!-- 第四行：上传提示文字 -->
                <div class="header-row fourth-row">
                    <div class="upload-tip-container">
                        <div class="upload-tip">支持上传不超过100MB的文件</div>
                    </div>
                </div>
                
            </div>

            <!-- 内容区域 -->
            <div class="card-content">
                <!-- 表格区域 -->
                <div class="table-section">
                    <el-table :data="tableData" v-loading="loading" :header-cell-style="{
                        background: '#f8f9fa',
                        color: '#606266',
                        fontWeight: '600'
                    }" stripe highlight-current-row class="file-table">
                        <el-table-column prop="file_name" label="文档名称" min-width="200" show-overflow-tooltip>
                            <template #header>
                                <span class="column-header">
                                    <el-icon>
                                        <Document />
                                    </el-icon>
                                    文档名称
                                </span>
                            </template>
                        </el-table-column>

                        <el-table-column prop="create_date" label="创建时间" width="150" align="center">
                            <template #header>
                                <span class="column-header">
                                    <el-icon>
                                        <Clock />
                                    </el-icon>
                                    创建时间
                                </span>
                            </template>
                            <template #default="{ row }">
                                <span class="create-time">{{ formatDate(row.create_date) }}</span>
                            </template>
                        </el-table-column>

                        <el-table-column label="操作" width="280" fixed="right" align="center">
                            <template #header>
                                <span class="column-header">
                                    <el-icon>
                                        <Operation />
                                    </el-icon>
                                    操作
                                </span>
                            </template>
                            <template #default="{ row }">
                                <div class="action-buttons">
                                    <el-tooltip content="查看图片" placement="top">
                                        <el-button type="primary" size="small" @click="viewImage(row)" icon="Picture"
                                            class="action-btn" />
                                    </el-tooltip>

                                    <el-tooltip content="查看文本" placement="top">
                                        <el-button type="success" size="small" @click="viewText(row)" icon="Document"
                                            class="action-btn" />
                                    </el-tooltip>

                                    <el-tooltip content="开始解析" placement="top">
                                        <el-button type="warning" size="small" @click="startParsingHandler(row)"
                                            icon="Reading" class="action-btn" />
                                    </el-tooltip>

                                    <el-tooltip content="删除文档" placement="top">
                                        <el-button type="danger" size="small" @click="handleDelete(row)" icon="Delete"
                                            class="action-btn" />
                                    </el-tooltip>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>

                <!-- 分页区域 -->
                <div class="pagination-section" v-if="pagination.total > 0">
                    <el-pagination v-model:current-page="pagination.page" v-model:page-size="pagination.pageSize"
                        :total="pagination.total" :page-sizes="[10, 20, 50]"
                        layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                        @current-change="handlePageChange" class="custom-pagination" />
                </div>

                <!-- 空状态 -->
                <div class="empty-state" v-if="!loading && tableData.length === 0">
                    <el-empty description="暂无文档数据">
                        <el-button type="primary" @click="resetSearch">查看全部文档</el-button>
                    </el-empty>
                </div>
            </div>
        </el-card>

        <!-- 解析进度弹窗（保持不变） -->
        <el-dialog v-model="parseDialogVisible" title="文件解析进度" width="600px" :close-on-click-modal="false"
            :close-on-press-escape="false" :show-close="false">
            <div class="parse-progress">
                <div class="progress-item">
                    <span class="label">文字解析:</span>
                    <el-progress :percentage="textProgress" status="success" :text-inside="true" :stroke-width="20" />
                    <span class="count">{{ textCount }} 字符</span>
                </div>

                <div class="progress-item">
                    <span class="label">图片提取:</span>
                    <el-progress :percentage="imageProgress" status="warning" :text-inside="true" :stroke-width="20" />
                    <span class="count">{{ imageCount }} 张图片</span>
                </div>

                <div class="progress-item">
                    <span class="label">表格解析:</span>
                    <el-progress :percentage="tableProgress" status="exception" :text-inside="true"
                        :stroke-width="20" />
                    <span class="count">{{ tableCount }} 个表格</span>
                </div>
            </div>

            <template #footer>
                <el-button v-if="parseComplete" type="primary" @click="closeParseDialog">
                    完成
                </el-button>
                <el-button v-else :disabled="cancelling" @click="cancelParse">
                    {{ cancelling ? '取消中...' : '取消解析' }}
                </el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>

import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getFileList, deleteFile, uploadFile, startParsing } from '@/api/file'
import {Clock, Document, Operation} from "@element-plus/icons-vue";

const route = useRoute()
const router = useRouter()

// 从路由参数中获取知识库ID和名称
const knowbaseId = ref(route.params.knowbaseId)
const knowbaseName = ref(route.params.knowbaseName || '未知知识库')

// 搜索表单
const searchForm = reactive({
    keyword: '',
    knowbase_id: knowbaseId.value // 将知识库ID作为搜索条件
})

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 分页
const pagination = reactive({
    page: 1,
    pageSize: 10,
    total: 0
})



// 解析相关状态
const parseDialogVisible = ref(false)
const textProgress = ref(0)
const textCount = ref(0)
const imageProgress = ref(0)
const imageCount = ref(0)
const tableProgress = ref(0)
const tableCount = ref(0)
const parseComplete = ref(false)
const cancelling = ref(false)
const currentParsingFileId = ref(null)
let eventSource = null

// 加载数据
const fetchData = async () => {
    loading.value = true
    try {
        const params = {
            ...searchForm,
            page: pagination.page,
            page_size: pagination.pageSize
        }
        const response = await getFileList(params)
        const data = response.data.data
        tableData.value = data.list
        pagination.total = data.total_items
    } catch (error) {
        ElMessage.error('获取文档列表失败：' + error.message)
    } finally {
        loading.value = false
    }
}

// 日期格式化
const formatDate = (dateString) => {
    return new Date(dateString).toLocaleString()
}

// 搜索
const handleSearch = () => {
    pagination.page = 1
    fetchData()
}

// 重置搜索
const resetSearch = () => {
    searchForm.keyword = ''
    pagination.page = 1
    fetchData()
}

// 分页大小改变
const handleSizeChange = (size) => {
    pagination.pageSize = size
    fetchData()
}

// 页码改变
const handlePageChange = (page) => {
    pagination.page = page
    fetchData()
}

// 删除文档
const handleDelete = (row) => {
    ElMessageBox.confirm(`确定要删除文档 "${row.file_name}" 吗？`, '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            await deleteFile(row.file_id)
            ElMessage.success('删除成功')
            fetchData()
        } catch (error) {
            ElMessage.error('删除失败：' + error.message)
        }
    }).catch(() => { })
}

// 上传前处理 - 修改为100MB限制
const beforeUpload = (file) => {
    const isLt100M = file.size / 1024 / 1024 < 100 // 100MB限制
    if (!isLt100M) {
        ElMessage.error('文件大小不能超过100MB')
        return false
    }
    return true
}

// 处理上传
const uploadProgress = ref(0)

const handleUploadProgress = (event) => {
    if (event.total > 0) {
        uploadProgress.value = Math.round((event.loaded * 100) / event.total)
    }
}

const handleUpload = async (options) => {
    uploadProgress.value = 0 // 重置进度

    // const formData = new FormData()
    // formData.append('file', options.file)

    try {
        await uploadFile(knowbaseName.value, knowbaseId.value, options.file, {
            onUploadProgress: (progressEvent) => {
                if (progressEvent.total > 0) {
                    const percentCompleted = Math.round(
                        (progressEvent.loaded * 100) / progressEvent.total
                    )
                    uploadProgress.value = percentCompleted
                }
            }
        })
        ElMessage.success('上传成功')
        fetchData()
    } catch (error) {
        ElMessage.error('上传失败：' + error.message)
    } finally {
        setTimeout(() => {
            uploadProgress.value = 0
        }, 2000)
    }
}

// 查看图片（暂未实现）
const viewImage = (row) => {

    ElMessage.info('查看图片：' + row.file_name)
    router.push({
        name: 'ImageView',
        params: {
            file_id: row.file_id //传递文件ID作为参数
        },
        query: {
            file_name: row.file_name
        }
    }

    )
}

// 查看文本（暂未实现）
const viewText = (row) => {
    router.push({
        name: 'TextView',
        params: {
            file_id: row.file_id
        },
        query: {
            file_name: row.file_name
        }
    })
}


//开始解析
const startParsingHandler = async (row) => {
    currentParsingFileId.value = row.file_id

    //重置进度状态
    resetProgress()

    //打开弹窗
    parseDialogVisible.value = true

    try {

        const requestData = {
            file_id: row.file_id,
            file_path: row.file_path,
            file_name: row.file_name,
            knowbase_id: knowbaseId.value
        }

        // 启动解析任务 - 调用新的POST接口
        const response = await startParsing(requestData); // 这个函数需要修改（见下文）
        const taskId = response.data.task_id; // 从响应中获取后端生成的任务ID
        currentParsingFileId.value = taskId; // 存储当前任务ID


        //创建SSE连接监听进度
        eventSource = new EventSource(`${import.meta.env.VITE_API_BASE_URL || '/api'}/file/parse/process/${taskId}`)

        eventSource.onmessage = (event) => {
            const data = JSON.parse(event.data)
            updateProgress(data)
        }

        eventSource.onerror = (error) => {
            console.error('SSE连接错误:', error)
            if (eventSource.readyState === EventSource.CLOSED) {
                ElMessage.warning('解析进度连接已关闭')
            }
        }

    }
    catch (error) {
        ElMessage.error('开始解析失败: ' + error.message)
        parseDialogVisible.value = false
    }
}


// 更新进度显示
const updateProgress = (data) => {
    if (data.type === 'text') {
        textProgress.value = Number(data.percentage)
        textCount.value = Number(data.count)
    } else if (data.type === 'image') {
        imageProgress.value = Number(data.percentage)
        imageCount.value = Number(data.count)
    } else if (data.type === 'table') {
        tableProgress.value = Number(data.percentage)
        tableCount.value = Number(data.count)
    } else if (data.type === 'complete') {
        parseComplete.value = true
        if (eventSource) {
            eventSource.close()
        }
        ElMessage.success('文件解析完成')
    } else if (data.type === 'error') {
        ElMessage.error('解析错误: ' + data.message)
        parseDialogVisible.value = false
        if (eventSource) {
            eventSource.close()
        }
    }
}


// 重置进度状态
const resetProgress = () => {
    textProgress.value = 0
    textCount.value = 0
    imageProgress.value = 0
    imageCount.value = 0
    tableProgress.value = 0
    tableCount.value = 0
    parseComplete.value = false
    cancelling.value = false
}


// 关闭解析弹窗
const closeParseDialog = () => {
    parseDialogVisible.value = false
    if (eventSource) {
        eventSource.close()
    }
}


// 取消解析
const cancelParse = async () => {
    cancelling.value = true
    try {
        // 这里可以调用取消解析的API
        ElMessage.info('解析已取消')
        parseDialogVisible.value = false
        if (eventSource) {
            eventSource.close()
        }
    } catch (error) {
        ElMessage.error('取消解析失败: ' + error.message)
    } finally {
        cancelling.value = false
    }
}


// 返回知识库管理
const goBack = () => {
    router.push({ name: 'KnowledgeBase' })
}


// 组件卸载时关闭SSE连接
onUnmounted(() => {
    if (eventSource) {
        eventSource.close()
    }
})

// 初始化加载
onMounted(() => {
    fetchData()
})

</script>

<style lang="scss" scoped>
.file-list-container {
    padding: 4px;
    background: #f5f7fa;
    min-height: 100vh;

    .unified-card {
        border-radius: 12px;
        border: none;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        overflow: hidden;

        .card-header {
            padding: 6px;
            border-bottom: 1px solid #f0f0f0;
            background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);

            .header-row {
                display: flex;
                align-items: center;
                margin-bottom: 16px;

                &:last-child {
                    margin-bottom: 0;
                }

                &.first-row {
                    justify-content: flex-start;

                    .back-btn {
                        padding: 10px 20px;
                        border-radius: 8px;
                        font-weight: 500;
                    }
                }

                &.second-row {
                    justify-content: center;

                    .knowbase-title {
                        margin: 0;
                        font-size: 20px;
                        font-weight: 600;
                        color: #303133;
                        text-align: center;
                    }
                }

                &.third-row {
                    justify-content: space-between;
                    align-items: center;
                    flex-wrap: wrap;
                    gap: 16px;

                    .search-section {
                        flex: 1;
                        min-width: 300px;

                        .search-input {
                            width: 100%;
                        }
                    }

                    .action-buttons {
                        display: flex;
                        align-items: center;
                        gap: 12px;
                        flex-wrap: wrap;

                        .upload-btn {
                            padding: 10px 20px;
                            border-radius: 8px;
                            font-weight: 500;
                        }
                    }
                }

                 &.fourth-row {
                    justify-content: flex-end;;
                    margin-top: -8px;
                    margin-bottom: 0;

                    .upload-tip-container {
                        text-align: right;
                        width: 100%;
                        padding-right: 20px; 

                        .upload-tip {
                            font-size: 12px;
                            color: #909399;
                            display: inline-block;
                            padding: 4px 8px;
                            background: #f8f9fa;
                            border-radius: 4px;
                        }
                    }
                }

                
            }
        }

        .card-content {
            padding: 0;

            .table-section {
                padding: 6px;

                .file-table {
                    margin: 20px 0;

                    :deep(.el-table__header) {
                        th {
                            background: #f8f9fa;
                            font-weight: 600;
                        }
                    }

                    :deep(.el-table__body) {
                        tr:hover>td {
                            background: #f5f7fa !important;
                        }
                    }

                    .column-header {
                        display: flex;
                        align-items: center;
                        gap: 6px;
                    }

                    .create-time {
                        font-size: 13px;
                        color: #606266;
                    }

                    .action-buttons {
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        gap: 8px;

                        .action-btn {
                            padding: 6px;
                            border-radius: 6px;
                            transition: all 0.3s ease;

                            &:hover {
                                transform: translateY(-1px);
                                box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
                            }
                        }
                    }
                }
            }

            .pagination-section {
                padding: 20px 24px;
                border-top: 1px solid #f0f0f0;

                .custom-pagination {
                    justify-content: flex-end;
                }
            }

            .empty-state {
                padding: 60px 24px;
            }
        }
    }

    .parse-progress {
        padding: 10px 0;

        .progress-item {
            display: flex;
            align-items: center;
            margin-bottom: 15px;

            .label {
                width: 80px;
                font-weight: bold;
            }

            .el-progress {
                flex: 1;
                margin: 0 15px;
            }

            .count {
                width: 80px;
                text-align: right;
                color: #666;
                font-size: 12px;
            }
        }
    }
}

// 响应式设计
@media (max-width: 768px) {
    .file-list-container {
        padding: 16px;

        .unified-card {
            .card-header {
                padding: 16px;

                .header-row {
                    &.third-row {
                        flex-direction: column;
                        align-items: stretch;

                        .search-section {
                            min-width: 100%;
                        }

                        .action-buttons {
                            width: 100%;
                            justify-content: center;

                            
                        }
                    }
                }
            }

            .card-content {
                .table-section {
                    padding: 0 16px;

                    .action-buttons {
                        flex-wrap: wrap;
                        justify-content: center;
                    }
                }

                .pagination-section {
                    padding: 16px;
                }
            }
        }
    }
}


// 动画效果
.fade-enter-active,
.fade-leave-active {
    transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
    opacity: 0;
}
</style>